import sys
import os
pro_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
root_path = os.path.dirname(os.path.dirname(pro_path))
sys.path.extend([pro_path, root_path])

import matplotlib.pyplot as plt
import seaborn as sns

from aliyun.log.logclient import LogClient
from aliyun.log.getlogsrequest import GetLogsRequest
import requests
from db.es.es_service import ElasticsearchStorage
import pandas as pd
import datetime
import settings
import json
# 创建Elasticsearch客户端
es = ElasticsearchStorage()


def lineplot(df, period, start_date, end_date):
    data = []
    for i in range(len(df)):
        if pd.isnull(df.iloc[i, 0]):
            continue
        elif 'JD' not in df.iloc[i, 0]:
            continue
        elif df.iloc[i, 1] == 'user':
            continue
        elif '开始转人' in df.iloc[i, 2]:
            data.append([df.iloc[i, 4][:19].replace('T', ' '), 0, 1])
        else:
            data.append([df.iloc[i, 4][:19].replace('T', ' '), 1, 0])
    tmp_df = pd.DataFrame(data=data, columns=['datetime', 'MachineReply', 'HumanReply'])
    tmp_df['datetime'] = pd.to_datetime(tmp_df['datetime'])
    tmp_df.set_index('datetime', inplace=True)

    df_resampled = tmp_df.resample('{}T'.format(period)).sum()
    #df_resampled = df_resampled.reset_index()


    plt.figure(figsize=(30, 12))
    sns.lineplot(data=df_resampled)


    plt.title('HumanReply and MachineReply counts every {} minutes'.format(period))
    plt.xlabel('Time')
    plt.ylabel('Count')

    plt.savefig("{}-{}.png".format(start_date, end_date))

def post_file(filename):
    id_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=4bc8d9fa-bcc2-4a2e-8b96-c2ffbd205431&type=file"
    wx_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4bc8d9fa-bcc2-4a2e-8b96-c2ffbd205431"
    data = {'file': open(filename, 'rb')}

    response = requests.post(url=id_url, files=data)
    print(response.text)
    json_res = response.json()
    media_id = json_res['media_id']
    data = {"msgtype": "file",
            "file": {"media_id": media_id},
            "mentioned_list": []
            }
    result = requests.post(url=wx_url, json=data)

def get_log(start_date, end_date):

    accessKeyId = 'LTAI5tSUDKmzLYmEAS1C4XAs'
    accessKeySecret = 'rc2kilXMpWHxs1lyblsoC0wpqTsVcG'
    endpoint = 'cn-zhangjiakou.log.aliyuncs.com'
    project = 'qw-gpt'
    logstore = 'qw_gpt_prod'

    client = LogClient(endpoint, accessKeyId, accessKeySecret)

    # 获取日志
    qry = ''
    topic = ''
    # begin_time = int((datetime.datetime.now() - datetime.timedelta(days=1)).timestamp())
    # end_time = int(datetime.datetime.now().timestamp())

    start_date = '{} 16:25:00'.format(start_date)
    end_date = '{} 16:35:00'.format(end_date)

    # 将日期字符串转换为timestamp对象
    begin_time = datetime.datetime.timestamp(datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S'))
    end_time = datetime.datetime.timestamp(datetime.datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S'))

    req = GetLogsRequest(project, logstore, fromTime=begin_time, toTime=end_time, topic=topic, query=qry, line=100000, offset=0, reverse=False)

    res = client.get_logs(req)

    # 输出日志
    logs = res.get_logs()
    print(len(logs))
    idx = 0
    d = dict()

    for log in logs:
        content = log.contents.get('content', '')
        if '完整的消息' in content:
            l = list()
            idx += 1
            customer_id = content.split('INFO: userId:[')[-1].split(']')[0]
            dialouge = content.split('完整的消息:')[-1]
            try:
                dialogue = eval(dialouge)
            except:
                continue
            for i in dialogue:
                try:
                    #i.update({'msgtime': datetime.datetime.fromtimestamp(i['msgtime']/1000).strftime("%Y-%m-%d %H:%M:%S")})
                    l.append({k:v for k, v in i.items() if k in ['京东金融福利推荐官', '用户']})
                    #l.append({'京东福利推荐官': i['京东金融福利推荐官']})
                except Exception as e:
                    print(i['msgtime'])
                    print(str(e))


            d.update({customer_id: l})
    #print(idx)
    print(len(d))
    print(d)
    return d

def find_session_with_date(start_date, end_date):

    query = {
  "query": {
    "range": {
      "message_time": {
        "gte": "{}T16:30:00".format(start_date),
        "lt": "{}T16:30:00".format(end_date)
      }
    }
  },
  "sort": [
    {"session_id.keyword": "asc"},
    {"message_time": "asc"}
  ],
  "size": 10000
}
    # 执行查询
    results = es.search_documents(settings.QW_CONVERSATION_HISTORY_INDEX, query)
    complate_dialogue = get_log(start_date, end_date)
    if results:
        # 创建一个空的DataFrame
        data = []
        # 提取查询结果
        for idx, hit in enumerate(results):
            session_id = hit["_source"]["session_id"]
            role = hit["_source"]["role"]
            detail = hit["_source"]["text_info"]
            msg_time = hit["_source"]["message_time"]
            if idx > 0 and results[idx]["_source"]["session_id"] != results[idx-1]["_source"]["session_id"]:
                data[-1][-1] = str(complate_dialogue.get(data[-1][0], ['无']))
                data.append(["" for _ in range(5)])

            if role == 'assistant':
                data.append([session_id, role, json.loads(detail)['最终话术'], detail, msg_time, ''])
            else:
                data.append([session_id, role, detail, '', msg_time, ''])

        # 导出到Excel文件

        df = pd.DataFrame(columns=["session_id", "role", "content", "detail", "msg_time", "complete_content"], data=data)
        print(len(results), len(df), len(data))
        # df.sort_values(['session_id', 'msg_time'])
        print(len(results), len(df), len(data))
        df.to_excel("./{}-{}.xlsx".format(start_date, end_date), index=False)
        lineplot(df, 10, start_date, end_date)



if __name__ == '__main__':
    try:
        start_date = sys.argv[1]
        end_date = sys.argv[2]
    except:
        end_date = datetime.datetime.now().strftime('%Y-%m-%d')
        start_date = (datetime.datetime.now() + datetime.timedelta(hours=-24)).strftime("%Y-%m-%d")
    find_session_with_date(start_date, end_date)
    post_file("./{}-{}.xlsx".format(start_date, end_date))
    os.remove("./{}-{}.xlsx".format(start_date, end_date))
    post_file("./{}-{}.png".format(start_date, end_date))
    os.remove("./{}-{}.png".format(start_date, end_date))
